package cn.roadtrip.utilmodule.util.oss;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.roadtrip.utilmodule.util.DataBean;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.common.comm.ResponseMessage;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.aliyuncs.exceptions.ClientException;
import com.google.gson.Gson;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Component
@Slf4j
public class OSSImpl {
    @Autowired
    private OSSConfigs ossConfigs;

    private OSS initConfig() {
        Gson gson = new Gson();
        System.out.println("oss.config->" + ossConfigs);
        System.setProperty("OSS_ACCESS_KEY_ID", ossConfigs.getAccessKey());
        System.setProperty("OSS_ACCESS_KEY_SECRET", ossConfigs.getSecretKey());
        String endpoint = ossConfigs.getEndpoint();
        String bucketName = ossConfigs.getBucketName();
        EnvironmentVariableCredentialsProvider credentialsProvider = null;
        try {
            credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        } catch (ClientException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return new OSSClientBuilder().build(endpoint, credentialsProvider);
    }

    public DataBean uploadFile(File file) {
        OSS ossClient = initConfig();
        try {
            String objectName = "upload/" + DateUtil.year(new Date()) + "/" + DateUtil.month(new Date()) + "/" + DateUtil.dayOfMonth(new Date()) + "/" + UUID.randomUUID().toString()
                    + "." + FileUtil.extName(file.getName());
            log.info("上传得文件对象：{}", objectName);
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(ossConfigs.getBucketName(), objectName, file);
            // 如果需要上传时设置存储类型和访问权限，请参考以下示例代码。
            // ObjectMetadata metadata = new ObjectMetadata();
            // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
            // metadata.setObjectAcl(CannedAccessControlList.Private);
            // putObjectRequest.setMetadata(metadata);

            // 上传文件。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            log.info("etag->{}", result.getETag());
            if (result.getResponse() != null) {
                log.error("response!=null");
                log.error("uri->{}", result.getResponse().getUri());
                return DataBean.err("oss-err", result.getResponse().getErrorResponseAsString());
            }
            return DataBean.suc(ossConfigs.getViewDomain() + objectName, 1, "suc", "操作成功");
        } catch (OSSException oe) {
            log.error("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            log.error("Error Message:" + oe.getErrorMessage());
            log.error("Error Code:" + oe.getErrorCode());
            log.error("Request ID:" + oe.getRequestId());
            log.error("Host ID:" + oe.getHostId());
            return DataBean.err("oss-err", oe.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    public DataBean getList() {

        OSS ossClient = initConfig();
        try {
            // 列举文件。如果不设置keyPrefix，则列举存储空间下的所有文件。如果设置keyPrefix，则列举包含指定前缀的文件。
            ObjectListing objectListing = ossClient.listObjects(ossConfigs.getBucketName(), "upload/");
            List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
            for (OSSObjectSummary s : sums) {
                System.out.println("\t" + s.getKey());
            }
            return DataBean.sucEmpty();
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
            return DataBean.sucEmpty();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
